﻿using Architecture.Domain.Service;
using Architecture.Repository;
using Architecture.Repository.Impl;
using Architecture.Repository.Interface;
using Architeture.Domain;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace RBAC.ZhuBoLin.Extensions
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// this 拓展语法
        /// string 被扩展的类型
        /// </summary>
        /// <param name="para">扩展方法的值</param>
        /// <returns></returns>
        public static int ToInt(this string para)
        {
            int result = 0;
            if (int.TryParse(para, out result))//true 类型装换成功
            {
                return result;
            }
            else
            {
                return -999999;
            }
        }

        /// <summary>
        /// 拓展方法注入
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped<EFCoreContext>();

            services.AddScoped<IUserRepository, UserRepository>();
            services.AddScoped<IUserService, UserService>();

            services.AddScoped<IProvincelRepository, ProvincelRepository>();
            services.AddScoped<IProvinceService, ProvinceService>();

            services.AddScoped<ICityInfoRepository, CityInfoRepository>();
            services.AddScoped<ICityService, CityService>();

            services.AddScoped<ICountyRepository, CountyRepository>();
            services.AddScoped<ICountyService, CountyService>();


            services.AddScoped<IRoleRepository, RoleRepository>();
            services.AddScoped<IRoleService, RoleService>();

            services.AddScoped<MenuIrepsitory, Menurepsitory>();
            services.AddScoped<IMenuSerivice, MenuSerivice>();

            services.AddScoped<IRoleMenuRepsitory, RoleMenuRepsitory>();
            services.AddScoped<IRoleMneuService, RoleMneuService>();

            services.AddScoped<IAFLRepository, AFLRepository>();
            services.AddScoped<IAFLservice, AFLservice>();

            services.AddScoped<IGoodsRepsitory, GoodsRepsitory>();
            services.AddScoped<IGoodService, GoodService>();

            services.AddScoped<IAllPicRepsitory, AllPicRepsitory>();
            services.AddScoped<IAllPicService, AllPicService>();

            services.AddScoped<IFarmingRepsotory, FarmingRepsotory>();
            services.AddScoped<IFarmingService, FarmingService>();

            services.AddScoped<HealthCareRepository,IHealthCareRepository>();
            services.AddScoped<IHealthCareService, HealthCareService>();

            services.AddScoped<IEnterpriseRepository, EnterpriseRepository>();
            services.AddScoped<IEnterpriseService, EnterpriseService>();

            services.AddScoped<IslaughterRepository, slaughterRepository>();
            services.AddScoped<ISlaughterService, SlaughterService>();

            services.AddScoped<ImachRepository, machRepository>();
            services.AddScoped<IMachiningSerivce, MachiningSerivce>();

            services.AddScoped<IUserRoleRepository, UserRoleRepository>();

            return services;
        }

        /// <summary>
        /// 注册上下文类
        /// </summary>
        /// <typeparam name="db"></typeparam>
        /// <param name="services"></param>
        /// <param name="connectionString"></param>
        /// <param name="enableSqlIlog"></param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<db>(this IServiceCollection services, string? connectionString, bool enableSqlIlog) where db : DbContext
        {
            return services.AddDbContext<db>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null
                        );
                }).EnableSensitiveDataLogging();
                if (enableSqlIlog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();
                    }));
                }
            });
        }



        /// <summary>
        /// 注册jwt
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option =>
            {
                //取出秘钥
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                option.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    //验证接受者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    //验证是否国企
                    ValidateLifetime = true,
                    //验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                };
            });
        }
    }


}
